package cn.bfay.util;

import org.springframework.util.DigestUtils;

import java.util.Random;

/**
 * MD5Utils.
 *
 * @author wangjiannan
 */
public class MD5Utils {
    private static String encode(String input) {
        String output = DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(input.getBytes()).getBytes());
        return output;
    }

    public static String generateSalt() {
        // 生成一个16位的随机数
        Random random = new Random();
        StringBuilder sBuilder = new StringBuilder(16);
        sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
        int len = sBuilder.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sBuilder.append("0");
            }
        }
        return sBuilder.toString();
    }

    public static String passwordAddSaltWithMD5(String password, String salt) {
        password = encode(password + salt);
        password = encode(password + salt);
        return password.substring(28, 32) + password.substring(0, 8) +
            password.substring(20, 24) + password.substring(8, 16) +
            password.substring(24, 28) + password.substring(16, 20);
    }
}
